#include <iostream>
#include <cmath>
#include <algorithm>
#include <set>

using namespace std;

set<int> mp;
const int N = 1e7 +10;



int main()
{
	int n; cin >> n;
	mp.insert(-N); mp.insert(N);
	
	int ret = 0;
	cin >> ret; mp.insert(ret);
	for(int i = 2;i <= n;i++)
	{
		int x; cin >> x;
		auto it = mp.lower_bound(x);
		
		auto tmp = it;
		tmp--;
		int m = 0; m = min(abs (*it - x)  , abs( (*tmp) - x )) ;
		ret += m;
		mp.insert(x); 
		m = 0;
	}
	cout << ret << endl;
	return 0;
}
